package com.ruoyi.cderp.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cderp.mapper.DicCityMapper;
import com.ruoyi.cderp.domain.DicCity;
import com.ruoyi.cderp.service.IDicCityService;

/**
 * 地区字典Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-11
 */
@Service
public class DicCityServiceImpl implements IDicCityService
{
    @Autowired
    private DicCityMapper dicCityMapper;


    @Override
    public List<DicCity> selectDicCityList3() {
        return dicCityMapper.selectDicCityList3();
    }

    @Override
    public List<DicCity> selectDicCityList() {
        List<DicCity> list1 = dicCityMapper.selectDicCityList2();
        return buildTree(list1);
    }
    // 核心方法：将平铺列表转为三级树形结构
    private List<DicCity> buildTree(List<DicCity> regions) {
        Map<String, DicCity> regionMap = new HashMap<>();
        List<DicCity> roots = new ArrayList<>();
        // 存储省份节点
        // 第一次遍历：将所有节点存入Map，并识别根节点（parentId=0）
        for (DicCity region : regions) {
            regionMap.put(region.getId(), region);
            if (region.getParentId() == null) {
                roots.add(region);
            }
        }
        // 第二次遍历：建立父子关系
        for (DicCity region : regions) {
            if (region.getParentId() != null) {
                DicCity parent = regionMap.get(region.getParentId());
                if (parent != null) {
                    parent.getChildren().add(region);
                    processChildren(region,2);
                }
            }
        }
        return roots;
    }

    private void processChildren(DicCity node, int depth) {
        if (depth >= 3) {
            // 第三层（区级）清空children
            node.setChildren(null);
            // 或保留空列表但由@JsonInclude过滤
            return;
        }
        for (DicCity child : node.getChildren()) {
            processChildren(child, depth + 1);
        }
    }
}
